package com.newcoretech.platform_service.scanner;///

/// * @ProjectName: scanner
/// * @Author: qifanxin
/// * @CreateDate: 2022/3/22 10:47 上午
/// * Copyright: ©2022 NEW CORE Technology Co. Ltd. All rights reserved.
/// * @Description: 文件说明
///

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.util.Map;

//import com.google.zxing.*;
//import com.google.zxing.common.GlobalHistogramBinarizer;
//import com.google.zxing.common.HybridBinarizer;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:解析二维码图片
 */
public class QRCodeDecoder {

    private QRCodeDecoder() {
    }

    /**
     * 同步解析本地图片二维码。该方法是耗时操作，请在子线程中调用。
     *
     * @param picturePath 要解析的二维码图片本地路径
     * @return 返回二维码图片里的内容 或 null
     */
    public static String syncDecodeQRCode(Context context, String picturePath) {
        HmsScan[] res = ScanUtil.decodeWithBitmap(context, getDecodeAbleBitmap(picturePath), null);
        if (res != null && res.length != 0) {
            return res[0].originalValue;
        } else {
            return null;
        }
    }

    /**
     * 将本地图片文件转换成可解码二维码的 Bitmap。为了避免图片太大，这里对图片进行了压缩。感谢 https://github.com/devilsen 提的 PR
     *
     * @param picturePath 本地图片文件路径
     * @return
     */
    private static Bitmap getDecodeAbleBitmap(String picturePath) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picturePath, options);
            int sampleSize = options.outHeight / 400;
            if (sampleSize <= 0) {
                sampleSize = 1;
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(picturePath, options);
        } catch (Exception e) {
            return null;
        }
    }
}
